﻿using SqlSugar;
using WinformDevFramework.Core.Winform;
using WinformDevFramework.IServices;
using WinformDevFramework.IServices.System;
using WinformDevFramework.Models;

namespace WinformDevFramework
{
    public partial class FrmUser : BaseForm1
    {
        private ISysUserServices _sysUserServices;
        private IsysDeptServices _sysDeptServices;
        public FrmUser(ISysUserServices sysUserServices,IsysDeptServices sysDeptServices)
        {
            _sysUserServices=sysUserServices;
            _sysDeptServices=sysDeptServices;
            InitializeComponent();
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        public override void Init()
        {
            base.Init();
            //初始化 数据列表 列名称
            this.dataGridViewList.DataSource = GetAllUsers();
            this.dataGridViewList.Columns["Username"]!.HeaderText = "登录名";
            this.dataGridViewList.Columns["FullName"]!.HeaderText = "呢称";
            this.dataGridViewList.Columns["Sex"]!.HeaderText = "性别";
            this.dataGridViewList.Columns["Email"]!.HeaderText = "邮箱";
            this.dataGridViewList.Columns["PhoneNumber"]!.HeaderText = "手机号码";
            this.dataGridViewList.Columns["CreateTime"]!.HeaderText = "创建时间";
            this.dataGridViewList.Columns["LastLoginTime"]!.HeaderText = "最后登录时间";
            this.dataGridViewList.Columns["Status"]!.HeaderText = "状态";
            this.dataGridViewList.Columns["DeptName"]!.HeaderText = "部门";
            this.dataGridViewList.Columns["DeptID"].Visible = false;
            this.dataGridViewList.Columns["Password"].Visible = false;
            SetParentMenu(_sysDeptServices.Query());

            SetToolButtonStatus(formStatus);
            SetToolsButton();
        }

        public override void DataGridViewListDoubleClick(object? sender, DataGridViewCellEventArgs e)
        {
            base.DataGridViewListDoubleClick(sender, e);
            var g = (DataGridView)sender;
            var model = g.CurrentRow.DataBoundItem as sysUser;
            //给详情页设置数据
            this.txtID.Text = model.ID.ToString();
            this.txtUserName.Text = model.Username;
            this.txtFullName.Text = model.Fullname;
            this.cmbSex.Text = model.Sex;
            this.txtMail.Text = model.Email;
            this.txtPhoneNumber.Text = model.PhoneNumber;
            this.cbStatus.Checked = model.Status.Value;
            this.dateTimePickerCreateDate.Text = model.CreateTime.ToString();
            this.dateTimePickerLastLoginDate.Text = model.LastLoginTime.ToString();

            var pmenu = _sysDeptServices.QueryById(model.DeptID);
            if (pmenu != null)
            {
                TreeNode node = new TreeNode(pmenu.DeptName);
                node.Name = pmenu.ID.ToString();
                node.Tag = pmenu;
                this.DeptID.TreeView.SelectedNode = this.DeptID.TreeView.Nodes.Find(pmenu.ID.ToString(), true).FirstOrDefault();
                this.DeptID.Text = pmenu.DeptName;
                this.DeptID.Tag = pmenu.ID;
            }

            SetToolButtonStatus(formStatus);
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        private List<sysUser> GetAllUsers()
        {
            return _sysUserServices.QueryMuch<sysUser,sysDept,sysUser>((u, d) =>new object[]
                {
                    JoinType.Left,u.DeptID==d.ID
                },
                (u, d) =>new sysUser()
                {
                    ID = u.ID,
                    CreateTime = u.CreateTime,
                    Username = u.Username,
                    Fullname = u.Fullname,
                    Sex = u.Sex,
                    Email = u.Email,
                    PhoneNumber = u.PhoneNumber,
                    Status = u.Status,
                    LastLoginTime = u.LastLoginTime,
                    Password = u.Password,
                    DeptName = d.DeptName,
                    DeptID = u.DeptID,
                }
            );
        }

        public override void TabControlSelectingFunction(object? sender, TabControlCancelEventArgs e)
        {
            base.TabControlSelectingFunction(sender, e);
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void AddFunction(object sender, EventArgs e)
        {
            base.AddFunction(sender, e);
            SetToolButtonStatus(formStatus);
            dateTimePickerCreateDate.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            cmbSex.Text = "男";
        }
        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void EditFunction(object sender, EventArgs e)
        {
            base.EditFunction(sender, e);
            SetToolButtonStatus(formStatus);
            txtUserName.Enabled = false;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void SaveFunction(object sender, EventArgs e)
        {
            base.SaveFunction(sender, e);
            //if (ValidateData())
            {
                //新增
                if (string.IsNullOrEmpty(txtID.Text))
                {
                    sysUser newUser = new sysUser();
                    newUser.Username = txtUserName.Text;
                    newUser.Fullname = txtFullName.Text;
                    newUser.Sex = cmbSex.Text;
                    newUser.Email = txtMail.Text;
                    newUser.PhoneNumber=txtPhoneNumber.Text;
                    newUser.Status = cbStatus.Checked;
                    newUser.CreateTime = DateTime.Parse(dateTimePickerCreateDate.Text);
                    newUser.LastLoginTime = DateTime.Parse(dateTimePickerLastLoginDate.Text);
                    newUser.Password = "123456";
                    if (DeptID.TreeView.SelectedNode == null)
                    {
                        newUser.DeptID = int.Parse(DeptID.Tag.ToString());
                    }
                    else
                    {
                        newUser.DeptID = ((sysDept)DeptID.TreeView.SelectedNode.Tag).ID;
                    }
                    var id = _sysUserServices.Insert(newUser);
                    txtID.Text = id.ToString();
                    if (id > 0)
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }
                // 修改
                else
                {
                    sysUser user = _sysUserServices.QueryById(int.Parse(txtID.Text));
                    user.Username = txtUserName.Text;
                    user.Fullname = txtFullName.Text;
                    user.Sex = cmbSex.Text;
                    user.Email = txtMail.Text;
                    user.PhoneNumber = txtPhoneNumber.Text;
                    user.Status = cbStatus.Checked;
                    user.CreateTime = DateTime.Parse(dateTimePickerCreateDate.Text);
                    user.LastLoginTime = DateTime.Parse(dateTimePickerLastLoginDate.Text);
                    if (DeptID.TreeView.SelectedNode == null)
                    {
                        user.DeptID = int.Parse(DeptID.Tag.ToString());
                    }
                    else
                    {
                        user.DeptID = ((sysDept)DeptID.TreeView.SelectedNode.Tag).ID;
                    }
                    if (_sysUserServices.Update(user))
                    {
                        MessageBox.Show("保存成功！", "提示");
                    }
                }

                SetToolButtonStatus(formStatus);
                var menus = GetAllUsers();
                this.dataGridViewList.DataSource = menus;
            }
        }
        /// <summary>
        /// 撤销
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void CanelFunction(object sender, EventArgs e)
        {
            bool isAdd = formStatus == FormStatus.Add;
            base.CanelFunction(sender, e);
            SetToolButtonStatus(formStatus);
            btnEdit.Enabled = !isAdd;
            btnResetPW.Enabled=!isAdd;
            btnDel.Enabled = !isAdd;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DelFunction(object sender, EventArgs e)
        {
            base.DelFunction(sender, e);
            var result = MessageBox.Show("是否删除？", "确认", MessageBoxButtons.YesNoCancel);
            if (result == DialogResult.Yes)
            {
                _sysUserServices.DeleteById(Int32.Parse(txtID.Text));
                SetToolButtonStatus(formStatus);
                var menus = GetAllUsers();
                this.dataGridViewList.DataSource = menus;
            }
        }
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void CloseFunction(object sender, EventArgs e)
        {
          base.CloseFunction(sender, e);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void ResetPWFunction(object sender, EventArgs e)
        {
            var user = _sysUserServices.QueryById(int.Parse(txtID.Text));
            if (user != null)
            {
                user.Password = "123456";
                if (_sysUserServices.Update(user))
                {
                    MessageBox.Show("重置成功！", "提示");
                }
            }
        }
        /// <summary>
        /// 设置功能按钮状态
        /// </summary>
        public override void SetToolButtonStatus(FormStatus status)
        {
            switch (status)
            {
                case FormStatus.Add:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        btnResetPW.Enabled = false;
                        SetControlStatus(this.groupBox1, true);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
                case FormStatus.Edit:
                    {
                        btnAdd.Enabled = false;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = true;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = true;
                        btnResetPW.Enabled = true;
                        SetControlStatus(this.groupBox1, true);
                        break;
                    }
                case FormStatus.View:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        btnResetPW.Enabled = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Canel:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnResetPW.Enabled = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.First:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnResetPW.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Save:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = true;
                        btnSave.Enabled = false;
                        btnDel.Enabled = true;
                        btnCanel.Enabled = false;
                        btnResetPW.Enabled = true;
                        SetControlStatus(this.groupBox1, false);
                        break;
                    }
                case FormStatus.Del:
                    {
                        btnAdd.Enabled = true;
                        btnEdit.Enabled = false;
                        btnSave.Enabled = false;
                        btnDel.Enabled = false;
                        btnCanel.Enabled = false;
                        btnResetPW.Enabled = false;
                        SetControlStatus(this.groupBox1, false);
                        ClearControlsText(this.groupBox1);
                        break;
                    }
            }
        }
        //验证数据
        public override bool ValidateData()
        {
            bool result = false;
            if (string.IsNullOrEmpty(txtUserName.Text))
            {
                MessageBox.Show("账号不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(txtFullName.Text))
            {
                MessageBox.Show("昵称不能为空！");
                return result;
            }
            if (string.IsNullOrEmpty(DeptID.Text))
            {
                MessageBox.Show("部门不能为空！");
                return result;
            }
            result = true;
            return result;
        }

        /// <summary>
        /// 上级部门设置
        /// </summary>
        private void SetParentMenu(List<sysDept> menus)
        {
            DeptID.Nodes.Clear();
            List<TreeNode> nodes = new List<TreeNode>();
            foreach (var menu in menus)
            {
                TreeNode node = new TreeNode(menu.DeptName);
                node.Tag = menu;
                node.Name = menu.ID.ToString();
                nodes.Add(node);
            }

            foreach (var treeNode in nodes)
            {
                var menu = (sysDept)treeNode.Tag;
                treeNode.Nodes.AddRange(nodes.Where(p => menu.ID == ((sysDept)p.Tag).PDeptID).ToArray());
            }

            DeptID.Nodes.Add(nodes.Where(p => ((sysDept)p.Tag).PDeptID == 0).FirstOrDefault());
        }

    }
}
